package org.gradle;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;


public class EncoServerProgram extends Endpoint {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        super.onClose(session, closeReason);
        logger.info(session.getId() +"关闭");
    }

    @Override
    public void onError(Session session, Throwable thr) {
        super.onError(session, thr);
    }

    @Override
    public void onOpen(Session session, EndpointConfig config) {

        logger.info(session.getId() +"连接到服务器！");
        session.addMessageHandler(new MessageHandler.Whole<String>() {

            @Override
            public void onMessage(String message) {
                try {
                    logger.info(session.getId() +"发送了消息:" + message);
                    /*getBasicRemote()获得对RemoteEndpoint的一个引用。通过使用它可以马上返回一个消息给客户端
                     * 存在两种类型的RemoteEndpoint: RemoteEndpoint.Basic和RemoteEndpoint.Async
                     * RemoteEndpoint.Basic接口提供了一系列方法用于同步发送消息给客户端
                     * RemoteEndpoint.Async接口提供了一系列方法用于异步发送消息给客户端
                    */
                    session.getAsyncRemote().sendText(
                            "The server has received message:" + message);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        });
    }


}
